package com.sunop.userservice.service.impl;


import cn.dev33.satoken.stp.StpUtil;
import com.sunop.userservice.mapper.RoleMapper;
import com.sunop.userservice.service.SignInService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class SignInServiceImpl implements SignInService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RoleMapper roleMapper;

    // 用户签到
    public void signIn() {
        int userId = StpUtil.getLoginIdAsInt();
        LocalDate today = LocalDate.now();
        long offset = today.toEpochDay(); // 将日期转换为偏移量
        String signInKey = "signIn:" + userId;

        // 设置当天的签到状态为1
        redisTemplate.opsForValue().setBit(signInKey, offset, true);

        // 计算连续签到天数
        int consecutiveDays = getConsecutiveSignInDays(userId);

        // 计算积分
        int points = 1;
        if (consecutiveDays == 7) { // 连续签到满7天
            // 获取连续满勤周数
            String fullWeekStreakKey = "fullWeekStreak:" + userId;
            Integer fullWeekStreak = (Integer) redisTemplate.opsForValue().get(fullWeekStreakKey);
            if (fullWeekStreak == null) {
                fullWeekStreak = 0;
            }

            // 额外加分 = 3 + 连续满勤周数
            int extraPoints = 3 + fullWeekStreak;
            points += extraPoints;

            // 递增连续满勤周数
            redisTemplate.opsForValue().increment(fullWeekStreakKey, 1);
        } else if (consecutiveDays == 0) { // 中断签到，重置连续满勤周数
            String fullWeekStreakKey = "fullWeekStreak:" + userId;
            redisTemplate.opsForValue().set(fullWeekStreakKey, 0);
        }

        // 更新用户积分
        updateUserPoints(userId, points);
    }

    // 获取连续签到天数
    private int getConsecutiveSignInDays(int userId) {
        LocalDate today = LocalDate.now();
        String signInKey = "signIn:" + userId;
        int consecutiveDays = 0;

        for (int i = 0; i < 7; i++) {
            long offset = today.minusDays(i).toEpochDay();
            if (redisTemplate.opsForValue().getBit(signInKey, offset)) {
                consecutiveDays++;
            } else {
                break;
            }
        }

        return consecutiveDays;
    }

    // 更新用户积分
    private void updateUserPoints(int userId, int points) {
        String pointsKey = "userPoints:" + userId;
        redisTemplate.opsForValue().increment(pointsKey, points);
        roleMapper.updateUserPoints(userId, points);
    }

}